package org.jing.core.lang;

import org.jing.core.lang.annotation.SerializableType;
import org.jing.core.lang.data.BaseSerializableDto;
import org.jing.core.lang.data.Carrier;
import org.jing.core.lang.data.Creator;
import org.jing.core.logger.JingLogger;
import org.jing.core.util.ClassUtil;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Description: <br>
 *
 * @author bks <br>
 * @since 2023-09-19 <br>
 */
@SuppressWarnings("unused")
public final class DtoFactory {
    private static final JingLogger LOGGER = JingLogger.getLogger(DtoFactory.class);

    private static final ConcurrentHashMap<Class<? extends BaseSerializableDto>, Carrier> STATIC_DTO_MAP = new ConcurrentHashMap<>();

    private static final ConcurrentHashMap<Class<? extends BaseSerializableDto>, Creator<Carrier>> DYNAMIC_DTO_MAP = new ConcurrentHashMap<>();

    public static <T extends BaseSerializableDto> T createStaticDto(Class<T> type) {
        LOGGER.debug("serialize static dto:{} ", type);
        Carrier configC = STATIC_DTO_MAP.get(type);
        return configC.serialize(type);
    }

    public static synchronized void registerStaticDto(Class<? extends BaseSerializableDto> type, Carrier carrier) {
        ClassUtil.getAnnotationWithException(type, SerializableType.class);
        STATIC_DTO_MAP.put(type, carrier);
    }

    public static <T extends BaseSerializableDto> T createDynamicDto(Class<T> type) {
        LOGGER.debug("serialize static :{} ", type);
        Carrier configC = DYNAMIC_DTO_MAP.get(type).create();
        return configC.serialize(type);
    }

    public static synchronized void registerDynamicDto(Class<? extends BaseSerializableDto> type, Creator<Carrier> carrierCreator) {
        ClassUtil.getAnnotationWithException(type, SerializableType.class);
        DYNAMIC_DTO_MAP.put(type, carrierCreator);
    }
}
